package com.yanqu.road.server.manger.player;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.config.player.DecorationInfo;
import com.yanqu.road.entity.cricket.CricketData;
import com.yanqu.road.entity.cricket.UserCricketData;
import com.yanqu.road.entity.enums.*;
import com.yanqu.road.entity.estatewar.UserEstateWarData;
import com.yanqu.road.entity.estatewar.palace.UserPalaceData;
import com.yanqu.road.entity.interactive.InteractiveRecord;
import com.yanqu.road.entity.language.LanguageType;
import com.yanqu.road.entity.manor.ManorHelpResult;
import com.yanqu.road.entity.player.*;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.entity.winery.UserWineryData;
import com.yanqu.road.entity.winery.UserWineryInfoData;
import com.yanqu.road.exception.BusinessException;
import com.yanqu.road.logic.bussiness.player.*;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.PeakStrongholdWarProto;
import com.yanqu.road.pb.cricket.CricketProto;
import com.yanqu.road.pb.decoration.DecorationProto;
import com.yanqu.road.pb.estatewar.EstateWarProto;
import com.yanqu.road.pb.manor.ManorProto;
import com.yanqu.road.pb.player.PlayerProto;
import com.yanqu.road.pb.userinfo.UserInfoProto;
import com.yanqu.road.pb.winery.WineryProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.cricket.CricketModule;
import com.yanqu.road.server.gameplayer.module.manor.ManorModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.*;
import com.yanqu.road.server.gameplayer.module.skin.SkinModule;
import com.yanqu.road.server.gameplayer.module.vehicle.VehicleModule;
import com.yanqu.road.server.gameplayer.module.winery.WineryModule;
import com.yanqu.road.server.manger.DecorationMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.NormalActivityMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.manger.config.PatronsMgr;
import com.yanqu.road.server.manger.config.SkinMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.mammon.MammonMgr;
import com.yanqu.road.server.manger.manor.ManorMgr;
import com.yanqu.road.server.manger.palace.PalaceActivity;
import com.yanqu.road.server.manger.palace.PalaceActivityMgr;
import com.yanqu.road.server.manger.rank.RankMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.pb.CricketPb;
import com.yanqu.road.server.pb.PlayerPb;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.webservice.GamePublicFunction;
import com.yanqu.road.sync.message.SyncResponse;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.UUIDHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;


public class UserMgr extends TempMgr {

    private static Logger logger = LogManager.getLogger(UserMgr.class.getName());

    private static Map<Long, UserInfo> userInfoMap;

    public static String K = "";
    public static long T = 0;

    /**
     * 需要更新到跨服的数据
     */
    private static Map<Long,UserInfo> needUpdateToCrossMap = new ConcurrentHashMap<>();


    public static Map<Long, String> userSignValueMap = new ConcurrentHashMap<>();

    /**
     * 玩家包体ID
     */
    public static Map<Long, String> userPackageMarkMap = new ConcurrentHashMap<>();

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    @Override
    public boolean reloadData() {
        userInfoMap = UserBussiness.getCreateRoleUserInfoMap();
        checkNickName();
        return true;
    }

    private void checkNickName() {
        for (UserInfo userInfo : userInfoMap.values()) {
            String nickName = StringUtils.clearHeadAndTailEmpty(userInfo.getNickName());
            if (!Objects.equals(userInfo.getNickName(),nickName)) {
                userInfo.setNickName(nickName);
            }
        }

    }

    /**
     * 祝福值自动恢复
     */
    public static void autoRecoverHeart(UserInfo userInfo) {
        long nowTime = System.currentTimeMillis() / 1000;
        GamePlayer player = GamePlayerMgr.getOnlinePlayer(userInfo.getUserId());
        int recoverCount;
        synchronized (userInfo){
            recoverCount = (int) ((nowTime - userInfo.getLastHeartRecoverTime()) / GameConfig.HEART_RECOVER_TIME);
            long recoverTime = userInfo.getLastHeartRecoverTime() + recoverCount * GameConfig.HEART_RECOVER_TIME;
            if (recoverCount > 0) {
                int heartCount = userInfo.getHeartCount();
                if (heartCount > 0) {
                    heartCount = heartCount - recoverCount < 0 ? 0 : heartCount - recoverCount;
                    if(null == player){
                        BigInteger heartEffect = getHeartEffectEarnSpeed(userInfo.getBaseEarnSpeed()).multiply(BigInteger.valueOf(userInfo.getHeartCount() - heartCount));
                        userInfo.setEarnSpeed(userInfo.getEarnSpeed().subtract(heartEffect));
                        //赚速榜
                        RankMgr.changeUserRank(eBigRankType.Normal.getValue(), userInfo.getUserId(), userInfo.getEarnSpeed(), eRankType.EarnSpeed.getValue(), "");
                    }
                }
                if (heartCount < 0) {
                    heartCount = heartCount + recoverCount > 0 ? 0 : heartCount + recoverCount;
                    if(null == player){
                        BigInteger heartEffect = getHeartEffectEarnSpeed(userInfo.getBaseEarnSpeed()).multiply(BigInteger.valueOf(heartCount - userInfo.getHeartCount()));
                        userInfo.setEarnSpeed(userInfo.getEarnSpeed().add(heartEffect));
                        //赚速榜
                        RankMgr.changeUserRank(eBigRankType.Normal.getValue(), userInfo.getUserId(), userInfo.getEarnSpeed(), eRankType.EarnSpeed.getValue(), "");
                    }
                }
                userInfo.setHeartCount(heartCount);
                //设置恢复时间
                userInfo.setLastHeartRecoverTime(heartCount == 0 ? nowTime : recoverTime);
            }
        }
        if(recoverCount > 0){
            if(null != player) {
                player.getModule(AttributeModule.class).syncAttribute(ePlayerAttrType.HeartCount);
            }else {
                UserBussiness.updateLastHeartRecoverTimeAndEarnSpeed(userInfo.getUserId(), userInfo.getHeartCount(), userInfo.getLastHeartRecoverTime(), userInfo.getEarnSpeed());
            }
        }
    }

    public static UserInfo getUserInfo(long userId){
        if(userId > 0) {
            UserInfo userInfo = userInfoMap.get(userId);
            if (null == userInfo) {
                userInfo = UserBussiness.getUserInfoByUserId(userId);
                if (null != userInfo) {
                    userInfoMap.put(userId, userInfo);
                }
            }
            return userInfo;
        }
        return null;
    }

    public static List<UserInfo> getUserInfoByOpenId(String openId) {
        List<UserInfo> userInfos = new ArrayList<>();
        if (!StringUtils.isNullOrEmpty(openId)) {
            userInfos = UserBussiness.getUserInfoList(openId);
        }
        return userInfos;
    }

    public static UserInfo getUserInfoByUserAliasId(long userAliasId) {
        return UserBussiness.getUserInfoByUserAliasId(userAliasId);
    }

    public static UserBaseInfo getUserBaseInfo(long userId, long serverId){
        UserInfo userInfo = getUserInfo(userId);
        if (userInfo == null) {
            return null;
        }
        return parseUserBaseInfo(userInfo, serverId);
    }

    public static String getLanguage(long userId){
        String language = LanguageType.LANGUAGE_DEFAULT;
        UserInfo userInfo = getUserInfo(userId);
        if(null != userInfo){
            language = userInfo.getLanguage();
        }
        return language;
    }

    public static UserInfo getUserInfoByAliasId(long userAliasId){
        for(UserInfo userInfo : userInfoMap.values()){
            if(userInfo.getUserAliasId() == userAliasId){
                return userInfo;
            }
        }
        return null;
    }

    public static BigInteger getHeartEffectEarnSpeed(BigInteger baseEarnSpeed){
        BigDecimal tempEarnSpeed = new BigDecimal(baseEarnSpeed).multiply(BigDecimal.valueOf((double) GameConfig.HEART_ADDITION_EFFECT / 1000));
        return tempEarnSpeed.toBigInteger();
    }

    public static List<UserInfo> getUserInfoList(){
        return new ArrayList<>(userInfoMap.values());
    }

    public static void setUserInfo(UserInfo userInfo) {
        if (null == userInfo) {
            return;
        }
        userInfoMap.put(userInfo.getUserId(), userInfo);
    }

    public static void setBlackListEndTime(long userId, long blackListEndTime) {
        if (userInfoMap.containsKey(userId)) {
            userInfoMap.get(userId).setBlackListEndTime(blackListEndTime);
        }
    }

    public static long getLastLoginTime(long userId) {
        if (userInfoMap.get(userId) == null) {
            return 0;
        }
        return userInfoMap.get(userId).getLastLoginTime();
    }

    public static String getDecoration(long userId){
        UserInfo userInfo = getUserInfo(userId);
        if(null != userInfo){
            checkPlayerDecorationOverTime(userInfo, true);
            return userInfo.getDecoration();
        }
        return "";
    }

    public static String getUnionName(long userId){
        UserInfo userInfo = getUserInfo(userId);
        if(null != userInfo){
            if(!StringUtils.isNullOrEmpty(userInfo.getUnionUid())){
                return CrossUnionMgr.getUnionName(userInfo.getUnionUid());
            }
        }
        return "";
    }

    public static long getUnionAliasId(long userId){
        UserInfo userInfo = getUserInfo(userId);
        if(null != userInfo){
            if(!StringUtils.isNullOrEmpty(userInfo.getUnionUid())){
                return CrossUnionMgr.getUnionAliasId(userInfo.getUnionUid());
            }
        }
        return 0;
    }

    public static String getNickName(long userId){
        UserInfo userInfo = getUserInfo(userId);
        if(null != userInfo){
            return userInfo.getNickName();
        }
        return "";
    }

    public static String getBadge(long userId) {
        UserInfo userInfo = getUserInfo(userId);
        if (null != userInfo) {
            return userInfo.getBadge();
        }
        return "";
    }

    public static UserBaseInfo parseUserBaseInfo(UserInfo userInfo, long serverId){
        if(null == userInfo){
            return null;
        }
        UserBaseInfo userBaseInfo = new UserBaseInfo();
        userBaseInfo.setUserAliasId(userInfo.getUserAliasId());
        userBaseInfo.setNickName(userInfo.getNickName());
        userBaseInfo.setTitleId(userInfo.getTitleId());
        userBaseInfo.setDecoration(getDecoration(userInfo.getUserId()));
        userBaseInfo.setUnionAliasId(getUnionAliasId(userInfo.getUserId()));
        userBaseInfo.setUnionUid(userInfo.getUnionUid());
        userBaseInfo.setUnionName(getUnionName(userInfo.getUserId()));
        userBaseInfo.setVipExp(userInfo.getVipExp());
        userBaseInfo.setSex(userInfo.getSex());
        userBaseInfo.setEarnSpeed(userInfo.getEarnSpeed());
        userBaseInfo.setRegisterTime(userInfo.getRegisterTime());
        userBaseInfo.setServerId(serverId);
        userBaseInfo.setWorld(userInfo.getWorld());
        userBaseInfo.setContinent(userInfo.getContinent());
        userBaseInfo.setCountry(userInfo.getCountry());
        userBaseInfo.setProvince(userInfo.getProvince());
        userBaseInfo.setCity(userInfo.getCity());
        userBaseInfo.setLastLoginTime(userInfo.getLastLoginTime());
        userBaseInfo.setPrestige(userInfo.getPrestige().longValue());
        userBaseInfo.setHideVipAndAddress(userInfo.getHideVipAndAddress());
        userBaseInfo.setTotalAbility(userInfo.getTotalAbility());
        userBaseInfo.setTotalIntimacy(userInfo.getTotalIntimacy());
        //
        userBaseInfo.setHonors(0L);
        if(!StringUtils.isNullOrEmpty(userInfo.getUnionUid())){
            CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(userInfo.getUnionUid());
            if(unionInfo != null){
                userBaseInfo.setHonors(unionInfo.getHonors());
            }
        }
        userInfo.setBadge(getBadge(userInfo.getUserId()));
        return userBaseInfo;
    }

    public static InteractiveRecord initInteractiveRecord(long userId, int type, long operateUserId, UserBaseInfo operateBaseInfo) {
        InteractiveRecord interactiveRecord = new InteractiveRecord();
        interactiveRecord.setRecordUid(UUIDHelper.randomUUID(String.valueOf(GameServer.getInstance().getServerId())));
        interactiveRecord.setRecordTime(System.currentTimeMillis() / 1000);
        interactiveRecord.setUserId(userId);
        interactiveRecord.setInteractiveType(type);
        interactiveRecord.setOperateUserId(operateUserId);
        interactiveRecord.setOperateBaseInfo(operateBaseInfo);
        interactiveRecord.setInsertOption();
        return interactiveRecord;
    }

    /**
     * 查询
     */
    public static QueryPlayerResult queryPlayer(long watchUserId){
        QueryPlayerResult result = new QueryPlayerResult();
        UserInfo watchUserInfo = UserMgr.getUserInfo(watchUserId);
        if (null == watchUserInfo) {
            result.setRet(GameErrorCode.E_USER_NO_FOUND);
            return result;
        }
        result.setWatchUserInfo(watchUserInfo);
        result.setDecorationMap(MammonMgr.getUserDecorationMap(watchUserId));
        result.setUserBadgeList(BadgeMgr.getUserBadgeList(watchUserId));
        ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
        if (serverInfo != null) {
            if (eChannelType.isMainLandChannel(serverInfo.getChannelId())) {
                String location = getIpLocation(watchUserId);
                result.setIpLocation(location);
            }
        }
        return result;
    }

    /**
     * 拜访
     */
    public static WatchPlayerResult watchPlayer(long watchUserId){
        WatchPlayerResult result = new WatchPlayerResult();
        result.setWatchUserInfo(UserMgr.getUserInfo(watchUserId));
        UserEstateWarData userEstateWarData = EstateWarMgr.getUserEstateWarData(watchUserId);
        if (null != userEstateWarData) {
            result.setEstateType(userEstateWarData.getType());
            result.setEstatePos(userEstateWarData.getPos());
            result.setEstateSkinId(userEstateWarData.getEstateSkinId());
        }
        GamePlayer watchPlayer = GamePlayerMgr.getOnlinePlayer(watchUserId);
        if (null == watchPlayer) {
            result.setBuildingMap(UserBuildingBussiness.getUserBuildingMap(watchUserId));
            result.setPatronsMap(UserPatronsBussiness.getUserPatronsAndSkillMap(watchUserId));
            result.setVehicleMap(UserVehicleBussiness.getUserVehicleMap(watchUserId));
            Map<Integer, UserBeauty> userBeautyMap = UserBeautyBussiness.getUserBeautyMap(watchUserId);
            try {
                //指定国内渠道屏蔽同时拥有美女103001和103209的,屏蔽103209
                int channelId = ServerListMgr.getChannelId(GameServer.getInstance().getServerId());
                if (channelId == 201 ||
                        channelId == 221 ||
                        channelId == 231 ||
                        channelId == 241 ||
                        channelId == 301 ||
                        channelId == 311 ||
                        channelId == 321) {
                    if (userBeautyMap.containsKey(103001)){
                        userBeautyMap.remove(103209);
                    }
                }
            } catch (Exception e) {

            }
            result.setBeautyMap(userBeautyMap);
            if (!GamePublicFunction.isSystemOpen(watchUserId, eSystemId.Assistant.getValue())){         //4.4小助理换装增加判断
                result.setAssistantUnlock(0);
            } else {
                result.setAssistantUnlock(1);
            }
        } else {
            result.setBuildingMap(watchPlayer.getModule(BuildingModule.class).getBuildingMap());
            result.setPatronsMap(watchPlayer.getModule(PatronsModule.class).getUserPatronsMap());
            result.setVehicleMap(watchPlayer.getModule(VehicleModule.class).getUserVehicleMap());
            result.setBeautyMap(watchPlayer.getModule(BeautyModule.class).getBeautyMap());
            if (!SystemOpenMgr.systemOpen(watchPlayer,eSystemId.Assistant.getValue())){         //4.4小助理换装增加判断
                result.setAssistantUnlock(0);
            }else {
                result.setAssistantUnlock(1);
            }
        }
        if (null != watchPlayer) {
            watchPlayer.getModule(EarnSpeedModule.class).scheduleAddSilver();
        } else {
            UserMgr.autoRecoverHeart(result.getWatchUserInfo());
        }
        return result;
    }

    //拜访单个门客
    public static String watchPlayerPatron(long watchUserId,int patronsId){

        WatchPlayerResult result = new WatchPlayerResult();
        result.setWatchUserInfo(UserMgr.getUserInfo(watchUserId));
        GamePlayer watchPlayer = GamePlayerMgr.getOnlinePlayer(watchUserId);
        if (null != watchPlayer) {
            watchPlayer.getModule(EarnSpeedModule.class).scheduleAddSilver();
        } else {
            UserMgr.autoRecoverHeart(result.getWatchUserInfo());
        }
        return PatronsMgr.parsePatronsDetailInfoJsonStr(watchUserId, patronsId);
    }


    public static void checkPlayerDecorationOverTime(UserInfo userInfo, boolean isSendMsg){
        if(null == userInfo){
            return;
        }
        long nowTime = System.currentTimeMillis() / 1000;
        String decoration = userInfo.getDecoration();
        boolean change = false;
        if(StringUtils.isNullOrEmpty(decoration)){
            logger.warn("player decoration is empty");
            decoration = DecorationMgr.getDefaultDecoration(userInfo.getSex());
            change = true;
        }else {
            String[] decorationArr = decoration.split(DecorationMgr.SPLIT_SEPARATOR);
            List<String> decorationList = new ArrayList<>(Arrays.asList(decorationArr));
            //检测一下是否有加入默认的聊天气泡 或者缺少其他默认装饰的 修正
            change = DecorationMgr.fixDecoration(decorationList, userInfo.getSex());
            List<Integer> changeList = new ArrayList<>();
            for(String value : decorationList){
                int decorationId;
                if (StringUtils.isNullOrEmpty(value)) {
                    decorationId = 0;
                } else {
                    decorationId = Integer.parseInt(value);
                }
                int newDecorationId = decorationId;
                if (decorationId == 106805) {//之前投放百晓生装饰要失效
                    newDecorationId = 0;
                } else if (decorationId > 0 && GoodsMgr.isDecorationGoods(decorationId)) {
                    DecorationInfo decorationInfo = DecorationMgr.getDecorationInfo(decorationId);
                    if (null != decorationInfo && !decorationInfo.isFree()) {//加个非空判断，青松删配置炸了
                        GoodsInfo goodsInfo = GoodsMgr.getGoodsById(decorationId);
                        long param = goodsInfo.getParamList().get(0).longValue();
                        if (-1 != param) {//非永久的才检测
                            UserDecoration userDecoration = MammonMgr.getUserDecoration(userInfo.getUserId(), decorationId);
                            if (null == userDecoration) {
                                logger.info("player no find decoration:{}", decorationId);
                                newDecorationId = 0;
                            } else {
                                if (nowTime > userDecoration.getEndTime()) {
                                    logger.info("player decoration:{} has over time,end time:{}", decorationId, userDecoration.getEndTime());
                                    if (decorationInfo.getType() == eDecorationType.HeadFrame.getValue() || decorationInfo.getType() == eDecorationType.HonoraryTitle.getValue()) {
                                        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userInfo.getUserId());
                                        int maxDecorationId = 0;
                                        if (null != onlinePlayer) {
                                            List<Integer> decorationIdList = onlinePlayer.getModule(DecorationModule.class).getDecorationIdList(decorationInfo.getType());
                                            for (Integer tmpDecorationId : decorationIdList) {
                                                maxDecorationId = Math.max(tmpDecorationId, maxDecorationId);
                                            }
                                        }
                                        if (maxDecorationId != 0) {
                                            newDecorationId = maxDecorationId;
                                        } else {
                                            newDecorationId = DecorationMgr.getDefaultDecorationId(decorationInfo.getType(), userInfo.getSex());
                                        }
                                    } else {
                                        newDecorationId = DecorationMgr.getDefaultDecorationId(decorationInfo.getType(), userInfo.getSex());
                                    }
                                }
                            }
                        }
                    }
                } else if (decorationId > 0 && SkinMgr.isLTPMainRoleSkin(decorationId)) {
                    GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userInfo.getUserId());
                    Map<Integer, UserLTPMainRoleSkin> userLTPMainRoleSkinMap;
                    if (onlinePlayer != null) {
                        userLTPMainRoleSkinMap = onlinePlayer.getModule(SkinModule.class).getUserLTPMainRoleSkinMap();
                    } else {
                        userLTPMainRoleSkinMap = UserSkinBusiness.getUserLTPMainRoleSkinMap(userInfo.getUserId());
                    }
                    UserLTPMainRoleSkin userLTPMainRoleSkin = userLTPMainRoleSkinMap.get(decorationId);
                    if (userLTPMainRoleSkin == null) {
                        logger.error("player no find LTPMainRoleSkin:{}", decorationId);
                        newDecorationId = DecorationMgr.getDefaultCostume(userInfo.getSex(), userInfo.getDecoration());
                    } else {
                        if (nowTime > userLTPMainRoleSkin.getOverTime() / 1000) {
                            logger.info("player decoration:{} has over time,end time:{}", decorationId, userLTPMainRoleSkin.getOverTime());
                            if (onlinePlayer != null && onlinePlayer.getModule(AttributeModule.class).getUserAttributeMap().containsKey(ePlayerAttrType.DefaultSkin)) {
                                newDecorationId = Math.toIntExact(onlinePlayer.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.DefaultSkin));
                            } else {
                                newDecorationId = DecorationMgr.getDefaultCostume(userInfo.getSex(), userInfo.getDecoration());
                            }
                        }
                    }
                }
                changeList.add(newDecorationId);
                if(decorationId != newDecorationId){
                    change = true;
                }
            }
            if(change){
                decoration = StringUtils.listToString(changeList, DecorationMgr.SEPARATOR);
            }
        }
        if(change) {
            userInfo.setDecoration(decoration);
            RankMgr.changeUserInfo(userInfo.getUserId());
            if(isSendMsg) {
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(userInfo.getUserId());
                if (null != player) {
                    player.getModule(PlayerModule.class).syncDecoration();
                }
            }
        }
    }

    /**
     * 获取注册人数
     * @return
     */
    public static int getRegisterNum() {
        return UserBussiness.getRegisterUserCount();
    }

    public static String getUnionUid(long userId){
        UserInfo userInfo = getUserInfo(userId);
        if(null != userInfo){
            return userInfo.getUnionUid();
        }
        return "";
    }


    public static int manorHelpPlayer(GamePlayer player, long helpUserId, long helpServerId) {
        if(helpServerId == GameServer.getInstance().getServerId()){
            return localManorHelp(player, helpUserId);
        }else {
            return crossManorHelp(player, helpUserId, helpServerId);
        }
    }

    private static int localManorHelp(GamePlayer player, long helpUserId){
        GamePlayer helpPlayer = GamePlayerMgr.getOnlinePlayer(helpUserId);
        ManorHelpResult manorHelpResult;
        if (helpPlayer != null) {
            synchronized (ManorMgr.checkLockObj) {
                manorHelpResult = ManorMgr.onlineManorHelp(player.getUserId(), UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId()),
                        false, player, helpPlayer, helpUserId);
            }
        } else {
            synchronized (ManorMgr.offLineCheckLockObj) {
                manorHelpResult = ManorMgr.offlineManorHelp(player.getUserId(), UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId()),
                        false, player, helpUserId);
            }
        }
        if(manorHelpResult.getRet() != 0){
            return manorHelpResult.getRet();
        }
        player.getModule(CurrencyModule.class).addCurrency(manorHelpResult.getReward(), eLogMoneyType.Manor, eLogMoneyType.ManorHelpPlayerGet);
        ManorProto.HelpPlayerRespMsg.Builder respMsg = ManorProto.HelpPlayerRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setReward(PropertyHelper.parsePropertyToString(manorHelpResult.getReward()));
        respMsg.setHelpCount(manorHelpResult.getManorHelpCount());
        player.sendPacket(Protocol.U_MANOR_HELP_PLAYER, respMsg);

        long yieldCount = 0L;
        for (BigInteger value : manorHelpResult.getReward().getGoods().values()) {
            yieldCount += value.longValue();
        }
        ManorMgr.addRankActivityYieldCount(player.getModule(ManorModule.class).getUserManorData(), yieldCount, player);
        return 0;
    }

    private static int crossManorHelp(GamePlayer player, long helpUserId, long helpServerId){
        String unionUid = player.getUserInfo().getUnionUid();
        if(StringUtils.isNullOrEmpty(unionUid)){
            return GameErrorCode.E_UNION_NO_JOIN_UNION;
        }
        Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
        if(!memberMap.containsKey(helpUserId)){
            return GameErrorCode.E_CANNOT_MANOR_HELP_SAME_UNION;
        }

        if(player.getModule(ManorModule.class).isOpHelpUser(helpUserId)){
            return GameErrorCode.E_IS_CROSS_MANOR_HELP;
        }

        Property consume = PropertyHelper.parseStringToProperty(GameConfig.MANOR_HEART_CONSUME);
        if(!player.getModule(CurrencyModule.class).currencyIsEnough(consume)){
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }
        //预扣道具
        player.getModule(PreReduceModule.class).preReduce(consume);



        //发到跨服
        ManorProto.CrossHelpPlayerReqMsg.Builder crossMsg = ManorProto.CrossHelpPlayerReqMsg.newBuilder();
        crossMsg.setUserId(player.getUserId());
        crossMsg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.getUserBaseInfo(player.getUserId(), GameServer.getInstance().getServerId())));
        crossMsg.setHelpUserId(helpUserId);
        crossMsg.setHelpServerId(helpServerId);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_MANOR_HELP_PLAYER, crossMsg);
        GamePlayerMgr.sendPacket(player.getUserId(), pbMsg);

        return 0;
    }

    public static void addNeedUpdateToCrossMap(long userId,UserInfo userInfo){
        synchronized (needUpdateToCrossMap){
            if(userInfo != null){
                needUpdateToCrossMap.put(userId,userInfo);
            }
        }
    }

    /**
     * 批量更新玩家数据到跨服
     */
    public static void updateUserInfoToCross(){
        synchronized (needUpdateToCrossMap){
            for(UserInfo item : needUpdateToCrossMap.values()){
                PlayerProto.PlayerSimpleTempMsg.Builder msg = PlayerPb.parsePlayerSimpleTempMsg(item);
                GamePlayerMgr.sendPacket(item.getUserId(), YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_UPDATE_USER_BASE_INFO, msg));
                GamePlayerMgr.sendPacket(item.getUserId(), YanQuMessageUtils.buildMessage(CrossProtocol.C_CROSS_UPDATE_USER_BASE_INFO_TO_SERVER2, msg));
            }
            syncPalaceUserInfo(needUpdateToCrossMap);
            needUpdateToCrossMap.clear();
        }
    }

    private static void syncPalaceUserInfo(Map<Long,UserInfo> syncMap){
        try{
            PalaceActivity palaceActivity = PalaceActivityMgr.getInTimePalaceActivity();
            if(null != palaceActivity) {
                for (UserInfo data : syncMap.values()) {
                    UserPalaceData userPalaceData = palaceActivity.getUserPalaceData(data.getUserId());
                    if(null == userPalaceData){//没数据的就不同步了
                        continue;
                    }
                    EstateWarProto.PalacePlayerSyncMsg.Builder syncMsg = EstateWarProto.PalacePlayerSyncMsg.newBuilder();
                    syncMsg.setActivityId(palaceActivity.getPalaceActivityId());
                    syncMsg.setUserId(data.getUserId());
                    syncMsg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(UserMgr.parseUserBaseInfo(data, GameServer.getInstance().getServerId())));
                    YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_PALACE_PLAYER_INFO_SYNC, syncMsg);
                    GamePlayerMgr.sendPacket(0, pbMsg);
                }
            }
        }catch (Exception e){
            logger.error("syncPalaceUserInfo error:", e);
        }
    }

    public static String getUserSignValue(long userId) {
        return userSignValueMap.get(userId) == null ? "" : userSignValueMap.get(userId);
    }


    public static void recordUserSignValue(long userId, String value) {
        userSignValueMap.put(userId, value);
    }

    /**
     * 记录玩家包体ID
     * @param userId
     * @param packageMark
     */
    public static void recordUserPackageMark(long userId, String packageMark) {
        userPackageMarkMap.put(userId, packageMark);
    }

    /**
     * 获取玩家包体ID
     * @param userId
     * @return
     */
    public static String getUserPackageMark(long userId) {
        return userPackageMarkMap.getOrDefault(userId, "");
    }

    public static UserInfo getUserInfoInRAM(long userId){
        return userInfoMap.get(userId);
    }

    public static WineryProto.WineryVisitRespMsg.Builder wineryVisit(long visitId) {
        WineryProto.WineryVisitRespMsg.Builder builder = WineryProto.WineryVisitRespMsg.newBuilder();
        Map<Integer, UserWineryData> wineryDataMap;
        UserWineryInfoData userWineryInfoData;
        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(visitId);
        if (onlinePlayer == null) {
            wineryDataMap = UserWineryBusiness.getUserWineryDataMap(visitId);
             userWineryInfoData = UserWineryBusiness.getUserWineryInfoData(visitId);
            UserInfo userInfo = UserBussiness.getUserInfoByUserId(visitId);
            if (userInfo != null) {
                builder.setVisitName(userInfo.getNickName());
            }
        } else {
            wineryDataMap = onlinePlayer.getModule(WineryModule.class).getUserWineryDataMap();
            userWineryInfoData = onlinePlayer.getModule(WineryModule.class).getUserWineryInfoData();
            builder.setVisitName(onlinePlayer.getUserInfo().getNickName());
        }

        wineryDataMap.forEach((k, v) -> {
            WineryProto.WineryDataTemp.Builder temp = WineryProto.WineryDataTemp.newBuilder();
            temp.setWineryId(v.getWineryId());
            temp.setLevel(v.getLevel());
            builder.addWineryDataArray(temp);
        });
        if (userWineryInfoData != null) {
            builder.setBadgeLevel(userWineryInfoData.getBadgeLevel());
        } else {
            builder.setBadgeLevel(0);
        }
        return builder;
    }

    public static String getIpLocation(long userId) {
        String defaultLocation = "未知";
        String whiteLocation = WhiteListLocationMgr.getIpLocation(userId);
        if (!StringUtils.isNullOrEmpty(whiteLocation)) {
            return whiteLocation;
        }
        // 如果不是白名单
        UserInfo watchUserInfo = UserMgr.getUserInfo(userId);
        if (watchUserInfo != null) {
            String location = watchUserInfo.getIpLocation();
            if (!StringUtils.isNullOrEmpty(location)) {
                return location;
            }
        }
        return defaultLocation;
    }

    public static void userInfoDetail(long userId, int type, int relationId, UserInfoProto.UserInfoDetailRespMsg.Builder builder) {
        UserInfo userInfo = getUserInfo(userId);
        if (userInfo == null) {
            builder.setRet(GameErrorCode.E_USER_NO_FOUND);
            return ;
        }
        PlayerProto.PlayerBaseTempMsg.Builder parsePlayerBaseTempMsg = PlayerPb.parsePlayerBaseTempMsg(userInfo);
        builder.setInfo(parsePlayerBaseTempMsg);
        if (type == 1) {
            UserInfoProto.CricketUserInfo.Builder cricketUserInfoBuilder = UserInfoProto.CricketUserInfo.newBuilder();
            Map<Integer, CricketData> cricketDataMap = null;
            UserCricketData userCricketData = null;
            GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
            if (onlinePlayer != null) {
                cricketDataMap = onlinePlayer.getModule(CricketModule.class).getCricketDataMap();
                userCricketData = onlinePlayer.getModule(CricketModule.class).getUserCricketData();
            } else {
                cricketDataMap = UserCricketBussiness.getCricketDataMap(userId);
                userCricketData = UserCricketBussiness.getUserCricketData(userId);
            }

            if (cricketDataMap != null && userCricketData != null) {
                for (CricketData cricketData : cricketDataMap.values()) {
                    if (cricketData.getBattleWinTimes() == 0 && cricketData.getCurrentSeasonBattleWinTimes() == 0) {
                        continue;
                    }
                    UserInfoProto.CricketInfoTemp.Builder temp = UserInfoProto.CricketInfoTemp.newBuilder();
                    temp.setCricketId(cricketData.getCricketId());
                    temp.setBattleWinTimes(cricketData.getBattleWinTimes());
                    temp.setTitle(cricketData.getTitle());
                    temp.setLittleTitle(cricketData.getLittleTitle());
                    cricketUserInfoBuilder.addList(temp);
                }
                cricketUserInfoBuilder.setScore(userCricketData.getRankScore());
                cricketUserInfoBuilder.setCourtBadgeId(userCricketData.getCourtBadgeId());
            }

            builder.setCricketInfo(cricketUserInfoBuilder);
        } else if (type == 2) {
            Map<Integer, CricketData> cricketDataMap = null;
            GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
            if (onlinePlayer != null) {
                cricketDataMap = onlinePlayer.getModule(CricketModule.class).getCricketDataMap();
            } else {
                cricketDataMap = UserCricketBussiness.getCricketDataMap(userId);
            }

            if (cricketDataMap != null) {
                CricketData cricketData = cricketDataMap.get(relationId);
                if (cricketData != null) {
                    CricketProto.CricketTempMsg.Builder cricketTemp = CricketPb.parseCricketTemp(cricketData);
                    builder.setCricket(cricketTemp);
                }
            }
        } else if (type == 3) {
            Map<Integer, CricketData> cricketDataMap = null;
            GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
            if (onlinePlayer != null) {
                cricketDataMap = onlinePlayer.getModule(CricketModule.class).getCricketDataMap();
            } else {
                cricketDataMap = UserCricketBussiness.getCricketDataMap(userId);
            }

            if (cricketDataMap != null) {
                List<CricketData> dataList = new ArrayList<>();
                dataList.addAll(cricketDataMap.values());
                dataList.sort((o1, o2) -> {
                    Long power1 = o1.getCricketProperty().getAbility();
                    Long power2 = o2.getCricketProperty().getAbility();
                    return power2.compareTo(power1);
                });
                for (int i = 0; i < dataList.size() && i < GameConfig.CRICKET_FIGHT_DUEL_LIST_NUM; i++) {
                    CricketProto.CricketTempMsg.Builder cricketTemp = CricketPb.parseCricketTemp(dataList.get(i));
                    builder.addCricketList(cricketTemp);
                }
            }
        }
    }

    public static Map<Long, UserInfo> getUserInfoMap() {
        return userInfoMap;
    }

    public static int getDecorationByType(UserInfo userInfo, int decorationType){
        UserMgr.checkPlayerDecorationOverTime(userInfo, false);
        String decoration = userInfo.getDecoration();
        List<Integer> dataList = StringUtils.stringToIntegerList(decoration, DecorationMgr.SPLIT_SEPARATOR);
        while (dataList.size() < 7) {
            dataList.add(0);
        }
        if(eDecorationType.HeadIcon.getValue() == decorationType){
            return dataList.get(0);
        }else if(eDecorationType.HeadFrame.getValue() == decorationType){
            return dataList.get(1);
        }else if(eDecorationType.HonoraryTitle.getValue() == decorationType){
            return dataList.get(2);
        }else if(eDecorationType.Costume.getValue() == decorationType){
            return dataList.get(4);
        }else if(eDecorationType.ChatBubble.getValue() == decorationType){
            return dataList.get(5);
        }else if(eDecorationType.ChatTitle.getValue() == decorationType){
            return dataList.get(6);
        }
        return 0;
    }

    /**
     * 解析userAliasId，返回区服后缀，区服格式一定要是8位（666+00001），否则解析失败
     * @param userAliasId
     * @return 渠道ID + 返回数据 = 区服
     */
    public static String getServerSuffixByUserAliasId(long userAliasId) throws BusinessException{
        String userIdSuffix = getUserIdSuffixByUserAliasId(userAliasId);
        return userIdSuffix.substring(0, 5);
    }

    /**
     * 解析userAliasId，返回玩家ID后缀，区服格式一定要是8位（666+00001），否则解析失败
     * @param userAliasId
     * @return 渠道ID + 返回数据 = 玩家ID
     */
    public static String getUserIdSuffixByUserAliasId(long userAliasId) throws BusinessException {
        String userAliasIdStr = String.valueOf(userAliasId);
        if (userAliasIdStr.length() < 11) {
            throw new BusinessException(GameErrorCode.E_PLAYER_NO_FOUND);
        }
        //截取 后10位，
        String lastStr = userAliasIdStr.substring(userAliasIdStr.length() - 10);//后10位
        String firstStr = userAliasIdStr.replace(lastStr, "");//前几位，范围 ：1 - 100
        long firstNum = Long.parseLong(firstStr);
        firstNum = firstNum - 1;//范围 0-99
        //转换成2位的字符串 00 - 99
        String firstNumStr = String.format("%0" + 2 + "d", firstNum);
        //返回
        return firstNumStr + lastStr;
    }

    /**
     * 获取玩家区服信息，根据UserAliasId
     * @param userAliasId
     * @param activityId 0：过滤，非0：过滤非活动区服的玩家
     * @return k: 玩家ID,v：区服ID
     */
    public static Map<Long, Long> getUserServerByUserAliasId(long userAliasId, int activityId) throws BusinessException {
        Map<Long, Long> userServerMap = new HashMap<>();
        //获取指定截【取掉渠道的区服ID】
        String notChannelServerIdStr = getServerSuffixByUserAliasId(userAliasId);
        //遍历区服，得到符合的玩家，区服
        long serverId = ConfigHelper.getLong("serverId");
        int channelId = ServerListMgr.getChannelId(serverId);
        List<ServerInfo> allServerList = ServerListMgr.getChannelServerList(channelId);
        for (ServerInfo serverInfo : allServerList) {
            if (!ServerListMgr.isServerOpen(serverInfo)) {
                continue;
            }
            String serverIdStr = String.valueOf(serverInfo.getServerId());
            //区服ID去除渠道号。得到【截取掉渠道的区服ID】
            String targetNotChannelServerIdStr = serverIdStr.substring(3);
            String channelStr = serverIdStr.substring(0, 3);
            if (Objects.equals(targetNotChannelServerIdStr, notChannelServerIdStr)) {
                //获取玩家ID
                String userIdSuffix = getUserIdSuffixByUserAliasId(userAliasId);
                long userId = Long.parseLong(channelStr + userIdSuffix);
                userServerMap.put(userId, serverInfo.getServerId());
            }
        }

        //过滤下活动区服
        if (activityId > 0) {
            //获取活动信息
            ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
            if (activityInfo == null) {
                throw new BusinessException(GameErrorCode.E_ACTIVITY_NO_FOUND);
            }
            //判断活动是否已经过期
            if (!ActivityHelper.activityInShowTime(activityInfo)) {
                throw new BusinessException(GameErrorCode.E_COMMON_ACTIVITY_NO_IN_TIME);
            }
            if (activityInfo.getType() != eActivityType.QiXiActivity.getValue()) {
                Set<Long> activityServerSet = new HashSet<>(activityInfo.getServerIdList());
                //过滤
                Iterator<Map.Entry<Long, Long>> iterator = userServerMap.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<Long, Long> entry = iterator.next();
                    long targetServerId = entry.getValue();
                    if (!activityServerSet.contains(targetServerId)) {
                        //remove
                        iterator.remove();
                    }
                }
            }
        }

        return userServerMap;
    }

    /**
     * 查询玩家信息，根据UserAliasId
     * @param player
     * @param watchUserAliasId
     * @param activityId
     * @return
     */
    public static void queryPlayerByUserAliasId(GamePlayer player, long watchUserAliasId, int activityId){
        DecorationProto.QueryPlayerByUserAliasIdRespMsg.Builder respMsg = DecorationProto.QueryPlayerByUserAliasIdRespMsg.newBuilder();
        //解析出玩家ID,区服ID
        Map<Long, Long> userServerMap;
        try {
            userServerMap = UserMgr.getUserServerByUserAliasId(watchUserAliasId, activityId);
        } catch (BusinessException e) {
            respMsg.setRet(e.getCode());
            player.sendPacket(Protocol.U_QUERY_PLAYER_BY_USER_ALIAS_ID, respMsg);
            return;
        }
        if (userServerMap.isEmpty()) {
            respMsg.setRet(0);
            player.sendPacket(Protocol.U_QUERY_PLAYER_BY_USER_ALIAS_ID, respMsg);
            return;
        }
        //查询
        queryPlayerByUserServerMap(player, userServerMap);
    }


    /**
     * 根据用户ID和服务器ID查询玩家信息
     * @param player 游戏玩家对象
     * @param userServerMap 用户ID和服务器ID的映射关系
     */
    private static void queryPlayerByUserServerMap(GamePlayer player, Map<Long, Long> userServerMap) {
        DecorationProto.QueryPlayerByUserAliasIdRespMsg.Builder respMsg = DecorationProto.QueryPlayerByUserAliasIdRespMsg.newBuilder();
        int userServerMapSize = userServerMap.size();
        AtomicInteger checkNum = new AtomicInteger(); // 计算，记录回包次数，回包次数 == userServerMap.size()，才返回给客户端
        for (Map.Entry<Long, Long> entry : userServerMap.entrySet()) {
            long watchUserId = entry.getKey();
            long watchServerId = entry.getValue();
            // 到各自区服去查询
            if (watchServerId == GameServer.getInstance().getServerId()) {
                // 本区服，不需要跨服查询
                UserInfo userInfo = getUserInfo(watchUserId);
                if (userInfo != null) {
                    PlayerProto.PlayerBaseInfoTemp.Builder baseInfoTemp = PlayerPb.parsePlayerBaseInfoTemp(userInfo);
                    respMsg.addUserData(baseInfoTemp);
                }
                // 都回包后，再组装包体回给客户端
                int num = checkNum.incrementAndGet();
                if (num == userServerMap.size()) {
                    respMsg.setRet(0);
                    player.sendPacket(Protocol.U_QUERY_PLAYER_BY_USER_ALIAS_ID, respMsg);
                }
            } else {
                // 非本区服，跨服查询
                UserInfoProto.UserInfoDetailReqMsg.Builder queryReqMsg = UserInfoProto.UserInfoDetailReqMsg.newBuilder();
                queryReqMsg.setUserId(watchUserId);
                queryReqMsg.setServerId(watchServerId);
                UserInfoProto.UserInfoDetailRespMsg.Builder queryRespMsg = UserInfoProto.UserInfoDetailRespMsg.newBuilder();
                CompletableFuture<SyncResponse> responseFuture = GamePlayerMgr.sendToGameServer(watchServerId, GameProtocol.S_USER_INFO_DETAIL_SERVICE, player.getUserId(), queryReqMsg, queryRespMsg);
                responseFuture.thenAccept(syncResponse -> {
                    int num = checkNum.incrementAndGet();
                    if (syncResponse.getErrorCode() == 0) {
                        if (queryRespMsg.getRet() == 0) {
                            PlayerProto.PlayerBaseInfoTemp.Builder baseInfoTemp = PlayerProto.PlayerBaseInfoTemp.newBuilder();
                            baseInfoTemp.setUserId(watchUserId);
                            baseInfoTemp.setPlayerBaseData(queryRespMsg.getInfo());
                            respMsg.addUserData(baseInfoTemp);
                        }
                    }
                    // 都回包后，再组装包体回给客户端
                    if (num == userServerMapSize) {
                        respMsg.setRet(0);
                        player.sendPacket(Protocol.U_QUERY_PLAYER_BY_USER_ALIAS_ID, respMsg);
                    }
                });
            }
        }
    }

    /**
     * 商会分组用,更新玩家基础数据到活动跨服
     * @param userId
     * @param activityId
     * @param groupId
     */
    public static void syncUserBaseInfoToActivityCross(long userId, int activityId, int groupId) {
        PeakStrongholdWarProto.CrossPeakHoldUpdateUserBaseMsg.Builder updateUserBaseMsg = PeakStrongholdWarProto.CrossPeakHoldUpdateUserBaseMsg.newBuilder();
        updateUserBaseMsg.setActivityId(activityId);
        PeakStrongholdWarProto.UserBaseMsg.Builder userBuilder = PeakStrongholdWarProto.UserBaseMsg.newBuilder();
        userBuilder.setUserId(userId);
        UserBaseInfo userBaseInfo = UserMgr.getUserBaseInfo(userId, GameServer.getInstance().getServerId());
        userBuilder.setUserBaseMsg(PlayerBasePb.parsePlayerBaseTempMsg(userBaseInfo));
        updateUserBaseMsg.addUserBaseMsgList(userBuilder);
        GamePlayerMgr.sendUnionActivityGroupPacket(Protocol.C_PEAK_STRONGHOLD_UPDATE_USER_BASE_INFO, updateUserBaseMsg, 0, activityId, groupId);
    }

//    /**
//     * 根据用户别名ID和活动ID查询玩家信息
//     * @param player 游戏玩家对象
//     * @param watchUserAliasId 用户别名ID
//     * @param activityId 活动ID
//     */
//    public static void queryPlayerByUserAliasIdAndActivityId(GamePlayer player, long watchUserAliasId, int activityId) {
//        DecorationProto.QueryPlayerByUserAliasIdRespMsg.Builder respMsg = DecorationProto.QueryPlayerByUserAliasIdRespMsg.newBuilder();
//        //获取活动信息
//        ActivityInfo activityInfo = NormalActivityMgr.getActivityInfo(activityId);
//        if (activityInfo == null) {
//            respMsg.setRet(GameErrorCode.E_ACTIVITY_NO_FOUND);
//            player.sendPacket(Protocol.U_QUERY_PLAYER_BY_USER_ALIAS_ID_AND_ACTIVITY_ID, respMsg);
//            return;
//        }
//        //判断活动是否已经过期
//        if (!ActivityHelper.activityInShowTime(activityInfo)) {
//            respMsg.setRet(GameErrorCode.E_COMMON_ACTIVITY_NO_IN_TIME);
//            player.sendPacket(Protocol.U_QUERY_PLAYER_BY_USER_ALIAS_ID_AND_ACTIVITY_ID, respMsg);
//            return;
//        }
//        //解析出玩家ID,区服ID
//        Map<Long, Long> userServerMap;
//        try {
//            userServerMap = UserMgr.getUserServerByUserAliasId(watchUserAliasId);
//        } catch (BusinessException e) {
//            respMsg.setRet(e.getCode());
//            player.sendPacket(Protocol.U_QUERY_PLAYER_BY_USER_ALIAS_ID_AND_ACTIVITY_ID, respMsg);
//            return;
//        }
//        //判断活动玩家区服是否在活动区服中
//        Iterator<Map.Entry<Long, Long>> iterator = userServerMap.entrySet().iterator();
//        while (iterator.hasNext()) {
//            Map.Entry<Long, Long> entry = iterator.next();
//            if (!activityInfo.getServerIdList().contains(entry.getValue())) {
//                iterator.remove();  // 删除不在活动区服中的用户
//            }
//        }
//        //判断玩家MAP是否为空
//        if (userServerMap.isEmpty()) {
//            respMsg.setRet(0);
//            player.sendPacket(Protocol.U_QUERY_PLAYER_BY_USER_ALIAS_ID, respMsg);
//            return;
//        }
//        //查询
//        queryPlayerByUserServerMap(player, userServerMap);
//    }
}
